package Zuo.alg1;

/**
 * @author 24岁没牵过女人的手
 * 日期：2023/9/14 14:10
 * 文件描述：
 */
public class BinarySearch {
    public static int binarySearch(int[] arr, int a) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int midIndex = left + (right - left) / 2;
            if (arr[midIndex] == a) {
                return midIndex;
            } else if (arr[midIndex] < a) {
                left = midIndex + 1;
            } else if (arr[midIndex] > a) {
                right = midIndex - 1;
            }
        }
        return -1;
    }


    public static int binarySearchLeft(int[] arr, int a) {
        int left = 0;
        int right = arr.length;
        while (left < right) {
            int midIndex = left + (right - left) / 2;
            if (arr[midIndex] == a) {
                left = midIndex;
            } else if (arr[midIndex] < a) {
                left = midIndex + 1;
            } else if (arr[midIndex] > a) {
                right = midIndex;
            }
        }
        return left;
    }



    public static void main(String[] args) {
        int[] arr = {1, 3, 3, 3, 4, 4, 4, 4, 6, 6, 7, 8, 12};
        int target = 4;
        // int searchResult = binarySearch(arr, target);
        int leftSearchResult = binarySearchLeft(arr, target);
        // System.out.println(searchResult);
        System.out.println(leftSearchResult);
    }
}
